<?php
/*
 * code to authenticate user's login requests
*
*if either the username or password fields are blank redirect
 * to the login page and specifying the error in the query string */
$formError = 0;
if(!$_POST['userid']) $formError ++;
if(!$_POST['password']) $formError = $formError + 2;

if($formError > 0){
	header('location:login.php?errorcode='.$formError);
} else {
	// Create connection
	include("inc_files/utils/dbconnection.php");

	/*query for a record where userid and password are equal
	 * to the values passed to the form*/
	$query = "SELECT FirstName, LastName,
			 Password, Role FROM staff WHERE UserID=?";
	if($stmt = $mysqli -> prepare($query))	{

		//bind the userid and password from the form to the query
		$stmt -> bind_param("s", $userid);

		//sanitise the input data
		$userid = $mysqli->real_escape_string(trim($_POST['userid']));
		$enteredPassword = trim($_POST['password']);

		//execute the query
		$result = $stmt -> execute();

		//store the results
		$stmt -> store_result();

		//bind the results to variables
		$stmt -> bind_result($firstName, $lastName, $storedPassword, $userRole);

		//actually fetch the results
		$stmt -> fetch();

		//close the statement
		$stmt -> close();


		/*if the password entered by the user is the same as the soted
		 * passord then start a session, storing the user's ID, first and last names
		* in session variables
		*/
		if(crypt($enteredPassword, $storedPassword) == $storedPassword){

			session_start();
			$_SESSION['userid'] = $userid;
			$_SESSION['firstName'] = $firstName;
			$_SESSION['lastName'] = $lastName;
			$_SESSION['userRole'] = $userRole;
			header('location:home/home.php');


		} else {
			/*if 1 record not returned return to the login page
			 * and flag the page to display incorrect UserID/Password
			*/
			header('location:login.php?errorcode=4');

		}

	}
	//tidy up database connection
	$mysqli->close();

}
?>


